package com.minarto.display.loader {
	import com.minarto.display.loader.DisplayLoader;
	import flash.display.*;
	import de.polygonal.core.ObjectPool;
	import com.minarto.utils.GPool;
	
	
	/**
	 * @author KIMMINHWAN
	 */
	public class ImageLoader {
		static private var _instance:ImageLoader = new ImageLoader;
		static public function getInstance():ImageLoader {
			return	_instance;
		}
		
		
		private var	_dic:Object = {};
		
		public var sourceTag:String = "img://";
		
		
		
		public function ImageLoader(){
			if (_instance) {
				throw new Error("don't create instance");
			}
		}
		
		
		public function getContent($src:String, $onComplete:Function/** ($BitmapData)*/=null, $onIoError:Function/** ($src)*/=null):BitmapData{
			var p:ObjectPool, loader:DisplayLoader, bd:BitmapData;
			
			bd = _dic[$src];
			if(bd){
				if(Boolean($onComplete))	$onComplete(bd);
			}
			else{
				p = GPool.getPool(DisplayLoader);
				loader = p.object;
				loader.onComplete = function():void{
					var bm:Bitmap = loader.getContent() as Bitmap;
					
					loader.onComplete = null;
					loader.onIoError = null;
					p.object = loader;
					
					if(bm){
						bd = bm.bitmapData;
						_dic[$src] = bd;
						
						p = GPool.getPool(Bitmap);
						p.object = bm;
					}
					
					if(Boolean($onComplete))	$onComplete(bd);
				};
				loader.onIoError = function():void{
					loader.onComplete = null;
					loader.onIoError = null;
					p.object = loader;
					
					if(Boolean($onIoError))	$onIoError($src);
				};
				
				loader.load(sourceTag + $src);
			}
			
			return	bd;
		}
		
		
		public function delContent($src:String):void{
			delete _dic[$src];
		}
		
		
		public function clear():void{
			for(var p:String in _dic){
				delete _dic[p];
			}
		}
	}
}